package api

import (
	"github.com/gin-gonic/gin"
	"github.com/kataras/iris/v12"
	"zsc-boot/app/system_layer/model"
	"zsc-boot/app/system_layer/model/request"
	"zsc-boot/app/system_layer/service"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

var (
	ServiceDocumentApi     = new(serviceDocumentApi)
	serviceDocumentService = service.ServiceDocumentService
)

const (
	MAX_FILE_SIZE = 50 * iris.MB
)

type serviceDocumentApi struct {
}

// GetServiceDocument 查询文件详情
func (s *serviceDocumentApi) GetServiceDocument(ctx *gin.Context) {
	var id core.GetById
	_ = ctx.BindQuery(&id)
	if err, data := serviceDocumentService.GetServiceDocument(id.ID); err != nil {
		core.GetLogger().Error("查询失败!" + err.Error())
		web.FailResponse(ctx, err, "查询失败")
	} else {
		web.SuccessResponse(ctx, data)
	}
}

// GetServiceDocumentList 查询文件列表
func (s *serviceDocumentApi) GetServiceDocumentList(ctx *gin.Context) {
	var pageInfo request.ServiceDocoreumentSearch
	_ = ctx.BindQuery(&pageInfo)
	if err, list, total := serviceDocumentService.GetServiceDocumentList(pageInfo); err != nil {
		core.GetLogger().Error("查询失败!" + err.Error())

		web.FailResponse(ctx, err, "查询失败")
	} else {
		web.SuccessListResponse(ctx, list, total, pageInfo.Page, pageInfo.PageSize)
	}
}

// SingleFileUpload 上传单文件
func (s *serviceDocumentApi) SingleFileUpload(ctx *gin.Context) {
	var doc model.ServiceDocument
	_ = ctx.Bind(&doc)
	file, err := ctx.FormFile("file")
	if err != nil {
		web.FailResponse(ctx, err, "文件接收失败")
		return
	}
	if err, fileInfo := serviceDocumentService.SingleFileUpload(doc, file); err != nil {
		web.FailResponse(ctx, err, "文件接收失败")
	} else {
		web.SuccessResponse(ctx, fileInfo)
	}
}

// FileDownload 单文件下载
func (s *serviceDocumentApi) FileDownload(ctx *gin.Context) {
	var doc model.ServiceDocument
	_ = ctx.BindQuery(&doc)
	err, data := serviceDocumentService.GetServiceDocument(doc.ID)
	if err != nil {
		web.FailResponse(ctx, err, "没有此文件")
		return
	}
	// 浏览器禁止缓存
	ctx.Header("Cache-Control", "no-cache, private, max-age=0")
	ctx.FileAttachment(data.Path, data.FileName)
}

// View 单文件预览
func (s *serviceDocumentApi) View(ctx *gin.Context) {
	var doc model.ServiceDocument
	_ = ctx.BindQuery(&doc)
	err, data := serviceDocumentService.GetServiceDocument(doc.ID)
	if err != nil {
		web.FailResponse(ctx, err, "没有此文件")
		return
	}
	// 浏览器禁止缓存
	ctx.File(data.Path)
}

// Delete 删除
func (s *serviceDocumentApi) Delete(ctx *gin.Context) {
	var doc core.IdsReq
	_ = ctx.BindJSON(&doc)
	if err := orm.GetDb().Where("id in ?", doc.Ids).Delete(&model.ServiceDocument{}).Error; err != nil {
		web.FailResponse(ctx, err, "删除失败")
		return
	}
	// 浏览器禁止缓存
	web.SuccessResponse(ctx, nil)
}
